#include "utils.h"

int Utils::countOneSize(MatrixXi &mat)
{
    int nSum = 0;

    for(int i = 0; i < 3000; i++)
    {
        nSum += mat.coeff(0,i);
    }

    return nSum;
}

void Utils::outResult(int bestVal, MatrixXi &solve, std::string fileName)
{
    FILE *fp = fopen(fileName.c_str(),"wb");

    if(!fp)
    {
        return;
    }

    fprintf(fp,"f_best: %d\n",bestVal);
    for(int i = 0; i < solve.size(); i++)
    {
        fprintf(fp,"%d ",solve.coeff(0,i));
        if((i+1) % 50 == 0)
        {
            fprintf(fp,"\n");
        }
    }

    fclose(fp);
}

MatrixXi Utils::readSolve(char *fileName)
{
    char tpData[1024] = {0};
    char *ret = nullptr;

    FILE *fp = fopen(fileName,"rb");
    std::string data;
    int nIndex = 0;
    MatrixXi mat;
    int *matData;

    if(!fp)
    {
        assert(false);
    }

    mat.resize(1,3000);
    matData = mat.data();

    //jump first line
    ret = fgets(tpData,1024,fp);
    do
    {
        ret = fgets(tpData,1024,fp);
        if(ret)
        {
            std::stringstream stream(ret);
            while(true){
                data = "";
                stream>>data;
                if(data.size()>0)
                {
                    matData[nIndex] = atoi(data.c_str());
                    ++nIndex;
                }
                else
                {
                    break;
                }
            }
        }
    }
    while(ret);

    fclose(fp);

    return mat;
}
